package com.wjw.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.wjw.model.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class loginAction extends ActionSupport {

    //定义变量 接受页面的参数 与页面的name对应 并且提供set get方法
    private String userName;
    private String password;
    private List<User> userList;



    @Override
    public void validate() {
        //判断用户名是否为空
        if(StringUtils.isEmpty(userName)){
            addFieldError("NameError","用户名不能为空");
        }
    }

    @Override
    public String execute() throws Exception {
        //获取request
        //ActionContext.getContext().get("request");
        //解耦的方式获取session
        Map<String ,Object> session= ActionContext.getContext().getSession();
        session.put("userName",userName);
        session.put("password",password);
        userList=new ArrayList<>();
        userList.add(new User(1,"liu","daomei"));
        userList.add(new User(2,"weng","wuyu"));
        userList.add(new User(3,"hai","yumen"));
        userList.add(new User(4,"lin","aaa"));
        userList.add(new User(5,"meng","cda"));

        //直接定义成员变量就可以接受输出private List<User> userList;  可以不用session.put("userList",userList);
        //耦合的方式获取session
        HttpServletRequest request= ServletActionContext.getRequest();
//        HttpSession session2=request.getSession();
//        session2.setAttribute("userName",userName);
        //自定义逻辑字符串 与struts。xml的action->result标签里name对应
        return "login";
    }



    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }
}
